<?php
namespace app\index\model;
use think\Model;
use think\Db;
use think\Session;
class Weibo extends Model
{
    protected $table = 'threeuser';//表名
    protected $table_val; //数据

	//新浪微博获取access_token的第二部操作
    public static $url = "https://api.weibo.com/oauth2/access_token";


	//用户表添加
	public function add($param){
		  $this->guolv($param);
		  $res = Db::table($this->table)->where('id',$this->table_val['id'])->find();
		  if($res){
		    $bool = Db::table($this->table)->where('id',$this->table_val['id'])->update(['add_time' =>time()]);
		    if($bool){
		    	//返回第三方id;
		    	return $res['threeId'];
		    }
		  }else{
            // $boo = Db::table($this->table)->insert($this->table_val);
        
			return Db::name($this->table)->insertGetId($this->table_val);
       
		  }
	}


    public function get_token($code){
// echo $code;die;
    	// if(!Session::has('token')){
          //需要传递的参数
	    	$post_data = array(
					'client_id'=>'1022488053',
					'client_secret'=>'d4f0ef32f4ac838f53c4e5f9c24e5d0a',
					'grant_type'=>'authorization_code',
					'code'=>$code,
					'redirect_uri'=>'http://47.93.21.169/old/TP5/public/index.php/index/login/weibo'
			);

			//调用curl实现post提交
			$token = $this->curl_post($post_data);
			return $this->get_Info($token);

    }

    //获取第三方数据
    public function get_Info($token){
    	// var_dump($token);die;
           $url = 'https://api.weibo.com/2/users/show.json?access_token='.$token['access_token'].'&uid='.$token['uid'];
           $data = file_get_contents($url);
	       return json_decode($data,true);
    }

    public function curl_post($post_data){

    		$ch = curl_init();
			curl_setopt($ch,CURLOPT_URL,self::$url);
			curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			//POST数据
			curl_setopt($ch,CURLOPT_POST,1);
			//POST变量
			curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($post_data));
			$output = curl_exec($ch);
			curl_close($ch);
		    return json_decode($output,true);

    }

    	// 过滤字段
	public function guolv($data){
		
		$db = Db::name($this->table);
          //用户表的所有字段
		 $field = $db->getTableFields();
		 //过滤
		 foreach ($data as $k => $v) {
		 	  if(in_array($k,$field)){

	       	 	  $this->table_val[$k]=$v;

		 	  }
		 }
	}   
}